package com.xl.web.service.zoom;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import jodd.util.StringUtil;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.xl.base.annotation.DataSource;
import com.xl.base.page.Page;
import com.xl.base.page.PageBean;
import com.xl.core.constant.Globals;
import com.xl.core.enums.SourceEnum;
import com.xl.core.util.DateUtils;
import com.xl.core.util.zoom.ZoomRestAPI;
import com.xl.core.util.zoom.model.CreateMeeting;
import com.xl.web.dao.zoom.MeetingDao;
import com.xl.web.entity.zoom.Company;
import com.xl.web.entity.zoom.Invitation;
import com.xl.web.entity.zoom.Meeting;
import com.xl.web.entity.zoom.MeetingActionLog;
import com.xl.web.entity.zoom.SysUser;
import com.xl.web.entity.zoom.ZoomAccount;

@Service(value = "meetingService")
public class MeetingService<T extends Map> {
	@Resource
	private MeetingDao<Map> meetingDao;

	public Meeting  saveMeeting(SysUser user,
			CreateMeeting zoomMeeting) {
		Meeting meeting = combine2Meeting(user,zoomMeeting);
		meetingDao.saveMeeting(meeting);
		return meeting;
	}

	public void saveInvitation(SysUser sysUser, CreateMeeting zoomMeeting,
			JSONArray invitationList) {
		for (int i = 0; i < invitationList.size(); i++) {
			Invitation invitation = new Invitation();
			JSONObject json = invitationList.getJSONObject(i);
			invitation.setAccount(sysUser.getUserAccount());
			invitation.setUserName(sysUser.getUserName());
			invitation.setMobile(sysUser.getMobile());
			invitation.setEmail(sysUser.getEmail());
			invitation.setInvitationMode(json.getInteger("invitationMode"));
			invitation.setDept(sysUser.getDeptCode());
			invitation.setMeetingId(zoomMeeting.getUuid());
			meetingDao.saveInvitation(invitation);
		}
	}

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public List<ZoomAccount> queryAccountOrder(JSONObject paraMap) {
		int type = paraMap.getInteger("type");
		List<ZoomAccount> accounts = new ArrayList<ZoomAccount>();
		if (type == 1) {// 即时会议资源
			accounts = meetingDao.queryAccountOrder(paraMap);
		} else {
			accounts = meetingDao.queryAccountByschedule(paraMap);
		}
		return accounts;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public PageBean queryMyMeeting(Map paraMap) {
		// Meeting meeting,Page page
		Page page = new Page();
		if (paraMap.containsKey("pageNum")) {
			page.setPageNum(Integer.valueOf(paraMap.get("pageNum").toString()));
		}
		if (paraMap.containsKey("pageSize")) {
			page.setPageSize(Integer
					.valueOf(paraMap.get("pageSize").toString()));
		}
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<Meeting> meetings = meetingDao.queryMyMeeting(paraMap);
		PageBean pageBean = new PageBean(meetings);
		return pageBean;
	}
	
	//根据meetingId或meetingNumber and state查询会议信息
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public Meeting queryMeetings(Map paraMap) {
		List<Meeting> meetings = meetingDao.queryMeetings(paraMap);
		Meeting meeting = new Meeting();
		if(meetings!=null && meetings.size()>0){
			meeting = meetings.get(0);
		}
		return meeting;
		
	}

	public synchronized boolean checkTcpLimit(Meeting meeting) {
		boolean resultFlag = false;
		List<Company> companys = meetingDao.queryCompanyByMeeting(meeting);
		Company company = new Company();
		if (companys != null && companys.size() > 0) {
			company = companys.get(0);
			// 该公司并发不受限直接返回
			if (company.getTcpLimitFlag() == 0) {
				resultFlag = true;
			} else {
				// 如果公司配置为并行受限，则需要判断当前并发数和最大并发数
				if (company.getCurrentTcp() >= company.getTcpLimitMax()) {
					resultFlag = false;
				} else {
					resultFlag = true;
				}
			}

		} else {
			resultFlag = false;
		}

		return resultFlag;
	}

	public Company queryCompanyByMeeting(Meeting meeting) {
		List<Company> companys = meetingDao.queryCompanyByMeeting(meeting);
		Company company = new Company();
		if (companys != null && companys.size() > 0) {
			company = companys.get(0);
		}
		return company;

	}

	public SysUser queryUserByMeeting(Meeting meeting) {
		List<SysUser> sysUsers = meetingDao.queryUserByMeeting(meeting);
		SysUser sysUser = new SysUser();
		if (sysUsers != null && sysUsers.size() > 0) {
			sysUser = sysUsers.get(0);
		}
		return sysUser;

	}

	/**
	 * 开始会议做二步操作 1.更新会议状态， 2.更新会议对应的账号状态
	 * 
	 * @param meeting
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	public synchronized void meetingAction(Meeting meeting, String status) {
		MeetingActionLog meetingActionLog = new MeetingActionLog(
				meeting.getId(), status);
		List<Company> companys = meetingDao.queryCompanyByMeeting(meeting);
		Company company = companys.get(0);
		int currentTcp = company.getCurrentTcp();
		// 会议中只有一个start和一个end
		// 判断start和end已存在表中则不用再次插入
		//
		if (status.equals(Globals.MEETINGACTIONTYPESTARTED)) {
			meeting.setState(Globals.MEETINGSTATESTART);
			meetingDao.updateMeetingState(meeting);
			// 查询该STARTACTION是否已存在
			List<MeetingActionLog> meetingActionLogs = meetingDao
					.queryMeetingActionLog(meetingActionLog);
			if (meetingActionLogs == null || meetingActionLogs.size() == 0) {
				// 不存在则插入
				meetingDao.saveMeetingActionLog(meetingActionLog);
				// 再更新当前公司并发数
				company.setCurrentTcp(currentTcp + 1);
				meetingDao.updateCurrentTcp(company);
			}
		} else if (status.equals(Globals.MEETINGACTIONTYPEJOIN)) {
			meetingDao.saveMeetingActionLog(meetingActionLog);
			company.setCurrentTcp(currentTcp + 1);
			meetingDao.updateCurrentTcp(company);

		} else if (status.equals(Globals.MEETINGACTIONTYPELEAVE)) {
			meetingDao.saveMeetingActionLog(meetingActionLog);
			//会议状态为开会中的才会更新公司并发数//防止先ENDED再LEAVE
			if (meeting.getState() == Globals.MEETINGSTATESTART) {
				company.setCurrentTcp(currentTcp - 1);
				meetingDao.updateCurrentTcp(company);
			}

		} else if (status.equals(Globals.MEETINGACTIONTYPEENDED)) {
			meeting.setState(Globals.MEETINGSTATEFINISHED);
			meetingDao.updateMeetingState(meeting);
			// 查询该STARTACTION是否已存在
			List<MeetingActionLog> meetingActionLogs = meetingDao
					.queryMeetingActionLog(meetingActionLog);
			if (meetingActionLogs == null || meetingActionLogs.size() == 0) {
				// 不存在则插入
				meetingDao.saveMeetingActionLog(meetingActionLog);
				// 计算当前参数人数
				int joinMeetingCnts = meetingDao.calMeetingJoinCnts(meeting);
				company.setCurrentTcp(currentTcp - joinMeetingCnts);
				meetingDao.updateCurrentTcp(company);
			}

		}

	}

	/**
	 * 开始会议做二步操作 1.更新会议状态， 2.更新会议对应的账号状态
	 * 
	 * @param meeting
	 */
	
	   public void updateMeeting(Meeting meeting) { 
		   meetingDao.updateMeeting(meeting);
	      
	    }
	 
	public void saveInvitation(JSONArray invitationList) {
		Gson gson = new Gson();
		for (int i = 0; i < invitationList.size(); i++) {
			JSONObject invitationJson = invitationList.getJSONObject(i);
			Invitation invitation = gson.fromJson(
					invitationJson.toJSONString(), Invitation.class);
			meetingDao.saveInvitation(invitation);

		}

	}

	// 删除会议
	public void deleteMeeting(Meeting meeting) {
		// 将会议改为delete
		meetingDao.deleteMeeting(meeting);
	}
	/**
	 * 将zoomMeeting 和 user相关属性合并到 应用本身的meeting上
	 * @param user
	 * @param zoomMeeting
	 * @return
	 */
	public Meeting combine2Meeting(SysUser user,CreateMeeting zoomMeeting){
		Meeting meeting = new Meeting();
		meeting.setId(zoomMeeting.getUuid());
		meeting.setMeeting_number(zoomMeeting.getId());
		if (StringUtil.isEmpty(zoomMeeting.getPassword())) {
			meeting.setHas_password(false);
		} else {
			meeting.setHas_password(true);
		}
		meeting.setPassword(zoomMeeting.getPassword());
		meeting.setZoom_account(user.getEmail());
		meeting.setZoom_account_password(user.getPassword());
		meeting.setHost_id(user.getHostId());
		meeting.setPmi(user.getPmi());
		meeting.setToken(user.getToken());
		try {
			String start_time =  StringUtil.isEmpty(zoomMeeting
					.getStart_time()) == true ? zoomMeeting.getCreated_at()
					: zoomMeeting.getStart_time();
					meeting.setStart_time(start_time);		
		} catch (ParseException e) {
			e.printStackTrace();
		}
		meeting.setFormat_start_time(DateUtils.getTimeInMillis(meeting.getStart_time()));
		meeting.setDuration_hour(Integer.valueOf(zoomMeeting.getDuration()) / 60);
		meeting.setDuration_min(Integer.valueOf(zoomMeeting.getDuration()) % 60);
		meeting.setJbh(zoomMeeting.isOption_jbh());
		meeting.setStart_url(zoomMeeting.getJoin_url());
		meeting.setJoin_url(zoomMeeting.getJoin_url());
		meeting.setState(0);
		meeting.setUser_pmi(zoomMeeting.isOption_use_pmi());
		meeting.setRecord_url("");
		meeting.setParticipant_count(0);
		meeting.setIs_delete(false);
		meeting.setTopic(zoomMeeting.getTopic());
		meeting.setType(zoomMeeting.getType());
		meeting.setCreate_user_id(user.getUserId());
		meeting.setRepeatType(zoomMeeting.getRepeatType());
		return meeting;
	}

}
